# coding=utf-8

import sys
import time
import datetime
import json

from builtins import int

sys.path.append("..")
from common.mysql.connect import MysqlConnector
from common.tdengine.connect import TdengineConnector
from common.redis.connect import RedisConnector
from common.utils.time import turn_ts_to_date
from common.utils.time import get_yesterday_date
from common.utils.time import turn_date_to_ts


def get_stock_io_info(mysql_db, date):
    """ 根据日期获取库存io信息
    """
    ts_start = turn_date_to_ts(date)
    ts_end = ts_start + 60 * 60 * 24 - 1

    ids_sql = "SELECT distinct sp_id FROM ko_ku_history WHERE \
        add_at >= %d AND add_at <= %d" % (ts_start, ts_end)

    ids = '0'
    res_return = {'in':{'goods':{}}, 'out':{'goods':{}}}
    ids_tmp = mysql_db.select(ids_sql)
    if ids_tmp:
        for id in ids_tmp:
            ids = ids + ',' + str(id['sp_id'])
            res_return['in']['goods'][id['sp_id']] = 0
    
    res_sql = "SELECT * FROM ko_ku_history WHERE \
        add_at >= %d AND add_at <= %d" % (ts_start, ts_end)
    res = mysql_db.select(res_sql)

    if res:
        for record in res:
            if record['q_num'] >= record['h_num']:
                try:
                    res_return['out']['goods'][record['sp_id']] += record['num']
                except:
                    res_return['out']['goods'][record['sp_id']] = record['num']
            else:
                try:
                    res_return['in']['goods'][record['sp_id']] += record['num']
                except:
                    res_return['in']['goods'][record['sp_id']] = record['num']
    return res_return


def save_stock_in_info(mysql_db, date, io_info):
    """ 将io信息写入数据库
    """
    date_ts = turn_date_to_ts(date)
    save_sql = "INSERT INTO stock_io_info (date, io_info) VALUES (%d, '%s')" % \
        (date_ts, json.dumps(io_info))
    res = mysql_db.execute(save_sql)
    return res


if __name__ == '__main__':
    """ 商品(包括散珠配石和首饰盒)每日进出库数据统计
    """
    # 获取要处理的日期
    if len(sys.argv) == 2:
        # 外部传递进来
        date = sys.argv[1]
    else :
        # 默认取前一天的日期
        date = datetime.datetime.strftime(get_yesterday_date(), "%Y-%m-%d")

    # redis_14 = RedisConnector(14)
    # 3号库是老系统库存变动记录
    mysql_db3 = MysqlConnector(3)
    in_info = get_stock_io_info(mysql_db3, date)
    # print(res)
    
    mysql_db2 = MysqlConnector(2)
    save_res = save_stock_in_info(mysql_db2, date, in_info)
    if save_res:
        print('save success')
    else:
        print('save fail')
